﻿using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.TaskRob;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using System;
using System.Collections.Generic;
using System.Web.UI;
using H2.NET.Web.Management.Config.Service;
using System.Data;
using System.Web.UI.WebControls;
using H2.NET.DBUtility;
using System.Configuration;
using H2.NET.Web.Pages.SMD.AjaxTools;
using System.Linq;



namespace H2.NET.Web.Pages.SMD
{
    public partial class MdcItss : BasePage
    {


        public clsCommon clsCmm = new clsCommon();

        private string _step;
        #region 加载页面
        protected void Page_Load(object sender, EventArgs e)
        {


            DwzAssessment1.Category = "MdcItss";
            btn_submit.Visible = TaskAPI.IsAllowSubmit;
            //abortProcess.Visible = false;
            changeDeposit.Visible = false;
            if (!IsPostBack)
            {

                if (ReadOnly()) return;
                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    ScriptManager.RegisterStartupScript(this, GetType(), "info_tip", "$.jBox.tip('" + string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser) + "', 'info');", true);
                    return;
                }
                var ass = AssessmentService.GetBySubmitData(TaskAPI.Process, TaskAPI.Incident);
                var itss = BusinessService.GetItssByPi(TaskAPI.Process, TaskAPI.Incident);
                InitSelect();

                switch (TaskAPI.Step)
                {
                    case "Start Apply":

                        if (TaskAPI.Summary.Contains("退回"))
                        {
                            //  ddl_itsstype.Visible = false;
                            l_itsstype.Text = "流程驳回";//itss.ItssType;
                            ddl_itssreason.SelectedValue = itss.ItssReasonType;
                            businesskey.Attributes.Add("sn", itss.ItssBusinessKey);
                            if (itss.ItssType == "流程驳回")
                            {
                                abortProcess.Visible = true;
                                businesskey.Value = itss.ItssBusinessKey;
                            }
                            else if (itss.ItssType == "保证金调整")
                            {
                                changeDeposit.Visible = true;
                                dealercode.Value = itss.DealerCode;
                                authid.Value = itss.AuthID;
                                fullsetsn.Value = itss.Fullsetsn;
                                olddeposit.Text = itss.OldDeposit.ToString("N");
                                newdeposit.Value = itss.NewDeposit.ToString("N");
                            }
                            reason.Value = itss.ItssReason;
                        }
                        else
                        {
                            abortProcess.Visible = true;
                            changeDeposit.Visible = true;
                        }
                        break;
                    default:
                        InitForm(itss);
                        break;
                }
            }
        }
        #endregion

        #region 只读表单
        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                assessment.Visible = true;
                btn_submit.Visible = false;
                ajaxUpload1.AllowUpload = false;
                ajaxUpload1.AllowDelete = false;
                DwzAssessment1.Visible = false;
                btn_submit.Visible = false;

                var itss = BusinessService.GetItssByPi(TaskAPI.Process, TaskAPI.Incident);
                if (itss == null)
                {
                    JsTip("该流程还没有提交过，没有任何数据！");
                    return true;
                }
                InitForm(itss);

                return true;
            }

            return false;
        }
        #endregion

        #region 提交表单
        private bool Send(ref string return_msg)
        {
            bool flag;
            try
            {
                #region 数据验证
                if (TaskAPI.Step == "Submit Data" && TaskAPI.IsAllowSubmit && !TaskAPI.Summary.Contains("退回")) // 如果是退回的情况，不存在验证
                {

                }

                if (DwzAssessment1.Assessment.Remark == "")
                {
                    if (DwzAssessment1.Assessment.Opinion == "2")
                    {
                        return_msg = "如果驳回此流程,请在状态备注中填写放弃流程的原因";
                        return false;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "0")
                    {
                        return_msg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }

                }

                clsCmm.clsDB.Storage("oleDB");

                //1.发机流程到最终确认已发机时，该流程不得驳回 2.设备报废转库存。保证金变更子流程未完成不得驳回
                string Opinion = string.Empty;
                string BusinessKey = businesskey.Value;
                string Sql = BusinessKey.Contains("NS") ? string.Format("select * from t_Assessment where Step='Delivery Device' and BusinessKey='{0}'", businesskey.Value) : BusinessKey.Contains("DD") ? string.Format("select * from t_Assessment where Process='Store Deposit Change' and Step='Finance Change' and BusinessKey='{0}'", businesskey.Value) : "";
                if (!string.IsNullOrEmpty(Sql))
                {
                    DataTable dt = clsCmm.clsDB.Query(Sql);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        Opinion = dt.Rows[0]["Opinion"].ToString();
                        if ((!string.IsNullOrEmpty(Opinion)) && Convert.ToInt32(Opinion) == 0)//  0为确认发机
                        {
                            return_msg = BusinessKey.Contains("NS") ? "该流程中的设备已发机,不允许做驳回！" : BusinessKey.Contains("DD") ? "该流程中保证金变更子流程未完成,不允许做驳回！" : "";
                            return false;
                        }
                    }
                }
                
                
                //string sql = string.Format("select * from t_Assessment where Step='Delivery Device' and BusinessKey='{0}'", businesskey.Value);
                //DataTable dt = clsCmm.clsDB.Query(sql);
                //if (dt != null && dt.Rows.Count > 0)
                //{
                //    Opinion = dt.Rows[0]["Opinion"].ToString();
                //    if((!string.IsNullOrEmpty(Opinion)) && Convert.ToInt32(Opinion) == 0)//  0为确认发机
                //    {
                //        return_msg = "该流程中的设备已发机,不允许做驳回！";
                //        return false;
                //    }
                //}

                ////2.设备报废转库存。保证金变更子流程未完成不得驳回
                //string sql2 = string.Format("select * from t_Assessment where Process='Store Deposit Change' and Step='Finance Change' and BusinessKey='{0}'", businesskey.Value);
                //DataTable dt2 = clsCmm.clsDB.Query(sql2);
                //if (dt2 != null && dt2.Rows.Count > 0)
                //{
                //    if (Convert.ToInt32(dt2.Rows[0]["Opinion"]) == 0)//0为未完成
                //    {
                //        return_msg = "该流程中保证金变更子流程未完成,不允许做驳回！";
                //        return false;
                //    }
                //}

                #endregion

                #region 引擎传值
                switch (TaskAPI.Step)
                {
                    case "Start Apply":
                        TaskAPI.Summary = "上级领导审批/驳回流程申请";
                        break;
                    case "HOWG Approved":
                        if (DwzAssessment1.Assessment.Opinion == "0")
                        {
                            TaskAPI.Summary = "(退回)提交itss申请 / 驳回流程申请";
                        }
                        else if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            TaskAPI.Summary = "系统管理员审批 / 驳回流程申请";
                        }

                        TaskAPI["HOWGApprove"] = DwzAssessment1.Assessment.Opinion;

                        break;
                    case "Recheck Approved":
                        if (DwzAssessment1.Assessment.Opinion == "0")
                        {
                            TaskAPI.Summary = "(退回)提交itss申请 / 驳回流程申请";
                        }
                        else if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            TaskAPI.Summary = "系统管理员审批 / 驳回流程申请";
                        }

                        TaskAPI["RecheckApproved"] = DwzAssessment1.Assessment.Opinion;

                        break;
                    case "SystemManager Approved":
                        if (DwzAssessment1.Assessment.Opinion == "0")
                        {
                            TaskAPI.Summary = "(退回)上级领导审批 / 驳回流程申请";
                        }
                        else if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            TaskAPI.Summary = "维护数据 / 驳回流程申请";
                        }

                        TaskAPI["SystemManagerApprove"] = DwzAssessment1.Assessment.Opinion;
                        break;
                    case "Maintain Data":
                        if (DwzAssessment1.Assessment.Opinion == "0")
                        {
                            TaskAPI.Summary = "(退回)系统管理员审批 / 驳回流程申请";
                        }
                        else if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            TaskAPI.Summary = "完成维护数据 / 驳回流程申请";
                        }

                        TaskAPI["MaintainApprove"] = DwzAssessment1.Assessment.Opinion;
                        break;
                }
                #endregion

                #region 提交步骤

                var step = string.Empty;
                Storage.TransactionExecute(o =>
                {
                    #region 审批意见记录

                    var ass = DwzAssessment1.Assessment;
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }

                    #endregion

                    var itss = BusinessService.GetItssByPi(TaskAPI.Process, TaskAPI.Incident);
                    switch (TaskAPI.Step)
                    {
                        case "Start Apply":
                            if ((TaskAPI.GetVariableBySingleValue("HOWGApprove")) == "")
                            {
                                itss.ItssType = "流程驳回"; //ddl_itsstype.SelectedValue;
                            }
                            itss.ItssReasonType = ddl_itssreason.SelectedValue;
                            itss.Process = TaskAPI.Process;
                            itss.Incident = TaskAPI.Incident;
                            itss.ItssReason = reason.Value;
                            if (itss.ItssType == "流程驳回")
                            {
                                itss.ItssBusinessKey = businesskey.Value;
                            }
                            else if (itss.ItssType == "保证金调整")
                            {
                                itss.DealerCode = dealercode.Value;
                                itss.AuthID = authid.Value;
                                itss.Fullsetsn = fullsetsn.Value;
                                itss.OldDeposit = decimal.Parse(AksRequest.GetFormString("h_olddeposit"));
                                itss.NewDeposit = decimal.Parse(newdeposit.Value);

                            }
                            Storage.Save(Storage.Context3, itss);
                            break;
                        case "HOWG Approved":
                            break;
                        case "SystemManager Approved":

                            break;
                        case "Maintain Data":
                            if (DwzAssessment1.Assessment.Opinion == "1")
                            {
                                if (l_itsstype.Text == @"流程驳回")
                                {
                                    //驳回流程更新子流程表，更新流程状态,数据处理
                                    // BusinessService.AbortByBusinesskey(itss.ItssBusinessKey, itss.ItssReason);
                                    //指向代办让其人工手动修改

                                    var restoreSql = string.Format("{0}.dbo.[proc_itssRebut] '" + itss.ItssBusinessKey + "','" + itss.ItssReason + "'", DbHelperSQL.GetDatabaseName("smdDB"));
                                    var r = DbHelperSQL.ExecuteSql(restoreSql);//返回受影响的数据行
                                    if (r > 0)
                                    {
                                        step = "Finish";
                                    }
                                }
                                else if (l_itsstype.Text == @"保证金调整")
                                {
                                    //调整保证金，记录变更日志
                                    BusinessService.DepositChange(itss.Fullsetsn, itss.OldDeposit, itss.NewDeposit, itss.ItssReason);
                                }
                            }
                            break;
                    }
                });

                // 变更列表
                TaskAPI["Content"] = ChangeLogService.GenerateExcel(TaskAPI);
                //   TaskAPI["AutoBusinessKey"] = "MDCItss";
                flag = TaskAPI.Send();

                //如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                if (TaskAPI.Step == "Start Apply")
                {
                    (t_smd_Itss._Process == TaskAPI.Process & t_smd_Itss._Incident == 0).Edit<t_smd_Itss>(Storage.Context3, p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });

                    (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });

                    (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });
                }
                else
                {
                    if (step == "Finish")
                    {
                        string StartUserID = TaskAPI.GetVariableBySingleValue("Applicator");//申请人
                        var user = (m_OrgChart.winID == StartUserID).ListFirst<m_OrgChart>(Storage.Context1);
                        var Itss = (t_smd_Itss._Incident == TaskAPI.Incident).ListFirst<t_smd_Itss>(Storage.Context3);
                        SendEmail(Itss, user);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                return_msg = ex.Message.Replace("\"", "\\\"");
                Logging.GetLogger().Error("调用MdcItss.aspx方法Send_Click出错：" + ex);
                flag = false;
            }
            return flag;
        }
        protected void btn_submit_Click(object sender, EventArgs e)
        {
            string return_msg = string.Empty;
            if (Send(ref return_msg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { closeWin(); } });", true);
            }
            else
            {
                return_msg = string.IsNullOrEmpty(return_msg) ? Resources.Global.C_00_Failed : return_msg;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.prompt('" + return_msg + "','提示', 'info');", true);
            }
        }
        #endregion

        #region 初始化下拉框
        private void InitSelect()
        {
            //ddl_itsstype.Items.Clear();
            var configService = new ConfigService();
            //var itsstype = configService.GetList("ParentId = (select configid from t_smd_Config where code='Itsstype') order by Seq").Tables[0];
            //ddl_itsstype.Items.Add(new ListItem("请选择", ""));
            //foreach (DataRow row in itsstype.Rows)
            //{
            //    ddl_itsstype.Items.Add(new ListItem(row["name"].ToString(), row["value"].ToString()));
            //}

            ddl_itssreason.Items.Clear();
            var itssreason = configService.GetList("ParentId = (select configid from t_smd_Config where code='itssReason') order by Seq").Tables[0];
            ddl_itssreason.Items.Add(new ListItem("请选择", ""));
            foreach (DataRow row in itssreason.Rows)
            {
                ddl_itssreason.Items.Add(new ListItem(row["name"].ToString(), row["value"].ToString()));
            }

        }
        #endregion

        #region 内部方法
        /// <summary>
        /// 前台显示
        /// </summary>
        private void InitForm(t_smd_Itss itss)
        {
            // ddl_itsstype.Visible = false;
            l_itsstype.Text = "流程驳回";// itss.ItssType;

            ddl_itssreason.Visible = false;
            l_itssreason.Text = itss.ItssReasonType;

            if (itss.ItssType == "流程驳回")
            {
                abortProcess.Visible = true;
                businesskey.Visible = false;
                l_businesskey.Text = itss.ItssBusinessKey;
            }
            else if (itss.ItssType == "保证金调整")
            {
                changeDeposit.Visible = true;
                dealercode.Visible = false;
                l_dealercode.Text = itss.DealerCode;

                authid.Visible = false;
                l_authid.Text = itss.AuthID;

                fullsetsn.Visible = false;
                l_fullsetsn.Text = itss.Fullsetsn;
                newdeposit.Visible = false;
                olddeposit.Text = itss.OldDeposit.ToString("N");
                l_newdeposit.Text = itss.NewDeposit.ToString("N");
            }
            reason.Visible = false;
            l_reason.Text = itss.ItssReason;
        }
        #endregion


        private void SendEmail(t_smd_Itss Itss, m_OrgChart User)
        {
            try
            {


                Handler _handler = new Handler();
                var UserName = string.Empty;
                #region 获得"选择流程号"步骤人邮箱
                DbHelperSQL.connectionString = PubConstant.GetConnectionString("bpmDB");
                using( DataTable dt = DbHelperSQL.Query(_handler.BuildSqlStr(Itss.ItssBusinessKey)).Tables[0])
                {
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataRow item in dt.Rows)
                        {
                            UserName += "'" + item["taskuser"].ToString().Trim() + "',";
                        }
                    }
                }
                DbHelperSQL.connectionString = PubConstant.GetConnectionString("oleDB");
                DataTable rows_bh = new DataTable();
                if (!string.IsNullOrWhiteSpace(UserName))
                {
                    UserName = UserName.Substring(0, UserName.Length - 1);
                    string sql_bh = string.Format(@"select  distinct CEmail from m_OrgChart where WinID in ({0})", UserName); //正在驳回的流程步骤
                    Logging.GetLogger().Info("获得选择流程号步骤人邮箱sql:" + sql_bh);
                    rows_bh = DbHelperSQL.Query(sql_bh).Tables[0]; //获得需要驳回的流程步骤邮箱
                }
                #endregion

                #region 当前驳回流程步骤人的邮箱
                var list = AssessmentService.FindByPI(Itss.Process, Itss.Incident);
                if (list == null) list = new List<t_Assessment>();
                string sql = string.Format(@"select  distinct org.CEmail from m_OrgChart org inner join t_Assessment ass on  ass.UserName=org.WinID
                     where Process='mdc itss' and BusinessKey='{0}'", list.FirstOrDefault().BusinessKey);
                Logging.GetLogger().Info("当前驳回流程步骤人的邮箱sql:" + sql);
                DataTable rows = DbHelperSQL.Query(sql).Tables[0]; //获得此流程的所有邮箱 
                #endregion


                TaskAPI["E_Content"] = string.Format("{0}申请的业务流程已做驳回操作，驳回流程业务流程号：{1}，驳回理由：{2}，请知悉", User.DisplayName, Itss.ItssBusinessKey, Itss.ItssReason);
                var Email_bh = string.Empty;
                if (rows_bh.Rows.Count > 0)
                {

                    foreach (DataRow item in rows_bh.Rows)
                    {
                        Email_bh += item["CEmail"].ToString() + ';';
                    }
                }
                var Email = string.Empty;
                if (rows.Rows.Count > 0)
                {


                    foreach (DataRow item in rows.Rows)
                    {
                        Email += item["CEmail"].ToString() + ';';
                    }
                }

                TaskAPI["R_MDC_Itss_Inform1"] = Email_bh.TrimEnd(';');
                TaskAPI["R_MDC_Itss_Inform2"] = Email.TrimEnd(';');
                TaskAPI["NotifyApprove"] = 1;
            }
            catch (Exception ex)
            {
                Logging.GetLogger().Error("调用MdcItss方法SendEmail出错：" + ex);
            }

        }

    }
}